#include "stm32f1xx_hal.h"
#include "DAC8552.h"
#include "pid.h"

float DAC_Value = 0;


void DAC8552_Init(void)
{
	__HAL_RCC_GPIOA_CLK_ENABLE();
	
	
	GPIO_InitTypeDef GPIO_InitStruct = {0}; 

	GPIO_InitStruct.Pin = CS_PIN|SCLK_PIN|DIN_PIN;
	GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
	GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
	HAL_GPIO_Init(GPIOx, &GPIO_InitStruct);
	
	SCLK_1;
	CS_1;
}

void DAC8552_WriteValueBySoftWare(uint32_t Data)
{
	uint16_t i = 0;
	Data<<=8;
	
	SCLK_0;
	CS_0;
	SCLK_1;
	
	for(i = 0; i<24;i++)
	{
		if(Data & 0x80000000)
		{
			DIN_1;
			
		}
		else 
		{
			DIN_0;
		}
		SCLK_0;
		
		Data <<= 1;
		SCLK_1;
	}
	CS_1;
	
}

//void DAC8552_WriteValue(SPI_HandleTypeDef* hspi, uint32_t Data)
//{
//	uint8_t TXBuff[3];
//	
//	Data &= 0x00ffffff;
//	
//	TXBuff[0] = (uint8_t)((Data >> 16) & 0xff);
//	Data &= 0x0000ffff;
//	TXBuff[1] = (Data >> 8) & 0xff;
//	Data &= 0x000000ff;
//	TXBuff[2] = (Data >> 0) & 0xff;
//	HAL_GPIO_WritePin(GPIOx, CS_PIN, GPIO_PIN_RESET);
//	
//	
//	//OLED_ShowNum(3,1,(uint8_t)HAL_GPIO_ReadPin(GPIOx, CS_PIN),2);
//	
//	HAL_SPI_Transmit(hspi, TXBuff, 3, HAL_MAX_DELAY);
//	
//	HAL_GPIO_WritePin(GPIOx, CS_PIN, GPIO_PIN_SET);
//	
//	
//}

uint32_t DAC8552_VoltageToData(float Vref, float Voltage, float fb)
{
	uint32_t Data = 0;
	
	if(Voltage >= Vref)
	{
		Voltage = Vref - fb + 0.04f; 
		hpidV.Sum_E = 0;
		hpidA.Sum_E = 0;
	}
	
	DAC_Value = Voltage;
	
	Data = (uint32_t)(65535 * Voltage / Vref);
	if(Data >= 65535)
	{
		Data = 65535;
		
	}
	
	Data &= 0x00ffff;
	return Data;
	
}

char str[20]={0};

void DAC8552_WriteB(float Voltage, float fb)
{
	uint32_t Data = 0;
	Data = DAC8552_VoltageToData(DAC8552_Vref, Voltage, fb);
	Data = DAC8552_ChannelB|Data;
	
	DAC8552_WriteValueBySoftWare(Data);
}

float DAC8552_GetValueForChannelB(void)
{
	return DAC_Value;
}

